@page "/fetchdata"
@page "/fetchdata/{StartDate:datetime}"
@inject HttpClient Http

<h1>Weather forecast</h1>

<p>This component demonstrates fetching data from the server.</p>

@if (forecasts == null)
{
    <p><em>Loading...</em></p>
}
else
{
    <table class='table'>
        <thead>
            <tr>
                <th>Date</th>
                <th>Temp. (C)</th>
                <th>Temp. (F)</th>
                <th>Summary</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var forecast in forecasts)
            {
                <tr>
                    <td>@forecast.DateFormatted</td>
                    <td>@forecast.TemperatureC</td>
                    <td>@forecast.TemperatureF</td>
                    <td>@forecast.Summary</td>
                </tr>
            }
        </tbody>
    </table>
    <p>
        <a href="fetchdata/@StartDate.AddDays(-5).ToString("yyyy-MM-dd")" class="btn btn-secondary float-left">
            ◀ Previous
        </a>
        <a href="fetchdata/@StartDate.AddDays(5).ToString("yyyy-MM-dd")" class="btn btn-secondary float-right">
            Next ▶
        </a>
    </p>
}

@functions {
    [Parameter] DateTime StartDate { get; set; }

    WeatherForecast[] forecasts;

    public override Task SetParametersAsync(ParameterCollection parameters)
    {
        StartDate = DateTime.Now;
        return base.SetParametersAsync(parameters);
    }

    protected override async Task OnParametersSetAsync()
    {
        forecasts = await Http.GetJsonAsync<WeatherForecast[]>(
            $"sample-data/weather.json?date={StartDate.ToString("yyyy-MM-dd")}");

        // Because StandaloneApp doesn't really have a server endpoint to get dynamic data from,
        // fake the DateFormatted values here. This would not apply in a real app.
        for (var i = 0; i < forecasts.Length; i++)
        {
            forecasts[i].DateFormatted = StartDate.AddDays(i).ToShortDateString();
        }
    }

    class WeatherForecast
    {
        public string DateFormatted { get; set; }
        public int TemperatureC { get; set; }
        public int TemperatureF { get; set; }
        public string Summary { get; set; }
    }
}
